﻿//创建提示对话框
function createModal(modalId, title, bodyContent, confirmCallback) {
    const existingModal = document.getElementById(modalId);
    if (existingModal) {
        existingModal.remove();
    }
    const modalHTML = `
    <div class="modal fade" id="${modalId}" data-bs-backdrop="static" data-bs-keyboard="true" tabindex="-1" aria-labelledby="${modalId}Label" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable">
            <div class="modal-content">
                <div class="modal-header">
                    <h1 class="modal-title fs-5" id="${modalId}Label">${title}</h1>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    ${bodyContent}
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" data-bs-dismiss="modal" id="confirmButton">确认(ESC)</button>
                </div>
            </div>
        </div>
    </div>`;

    document.body.insertAdjacentHTML('beforeend', modalHTML);
    document.getElementById('confirmButton').addEventListener('click', function () {
        if (confirmCallback instanceof Function) {
            confirmCallback();
        }
    });
}
//展示提示对话框
function showModal(modalId) {
    const modalElement = new bootstrap.Modal(document.getElementById(modalId));
    modalElement.show();
}

function createAlerts() {
    const alertPlaceholder = document.getElementById('liveAlertPlaceholder');

    // 添加CSS样式以使提示窗悬浮在整个页面上面并自动向下排列
    const style = document.createElement('style');
    style.innerHTML = `
        .alert-container {
            position: fixed;
            left: 50%;
            transform: translateX(-50%);
            z-index: 9999; /* 确保提示框在其他内容之上 */
        }
        .alert-container:not(:first-child) {
            margin-top: 10px; /* 提示框之间有10像素的间距 */
        }
    `;
    document.head.appendChild(style);

    function showAlert(message, type, autoClose, duration) {
        const wrapper = document.createElement('div');
        wrapper.className = 'alert-container';
        wrapper.innerHTML = [
            `<div class="alert alert-${type} alert-dismissible" role="alert">`,
            `   <div>${message}</div>`,
            '   <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>',
            '</div>'
        ].join('');

        // 计算新的top值
        const existingAlerts = alertPlaceholder.querySelectorAll('.alert-container');
        let topPosition = 20; // 初始距离顶部20像素
        if (existingAlerts.length > 0) {
            const lastAlert = existingAlerts[existingAlerts.length - 1];
            const lastAlertTop = lastAlert.offsetTop;
            const lastAlertHeight = lastAlert.offsetHeight;
            const marginTop = parseInt(window.getComputedStyle(lastAlert).marginTop, 10) || 0;
            topPosition = lastAlertTop + lastAlertHeight + marginTop;
        }
        wrapper.style.top = `${topPosition}px`;

        alertPlaceholder.append(wrapper);

        // 如果autoClose为true且传入了duration，则添加自动关闭的逻辑
        if (autoClose && duration) {
            setTimeout(() => {
                wrapper.remove();
            }, duration * 1000);
        }

        // 为关闭按钮添加事件监听器
        const closeButton = wrapper.querySelector('.btn-close');
        if (closeButton) {
            closeButton.addEventListener('click', () => {
                wrapper.remove();
            });
        }
    }

    // 绑定按钮点击事件
    const alertTrigger = document.getElementById('liveAlertBtn');
    if (alertTrigger) {
        alertTrigger.addEventListener('click', () => {
            showAlert('Nice, you triggered this alert message!', 'success', true, 5); // 5秒后自动关闭
        });
    }

    // 将showAlert函数挂载到全局对象上，以便可以在任何地方调用
    window.showAlert = showAlert;
}

createAlerts();

function fetchAll(apiUrl, requestOptions) {
    return fetch(apiUrl, requestOptions)
        .then(response => {
            if (!response.ok) {
                switch (response.status) {
                    case 400:
                        showAlert('HTTP响应状态 400 请求错误，可能引起的原因是请求参数不正确，请检查请求参数是否正确。', 'danger', true, 3);
                        break;
                    case 401:
                        showAlert('HTTP响应状态 401 未授权，可能引起的原因是未登录或登录已过期，请重新登录。', 'danger', true, 3);
                        localStorage.removeItem("token");
                        localStorage.removeItem("userMdules");    
                        localStorage.removeItem("userid");
                        localStorage.removeItem("username");
                        $('#loginBtn').text("用户登录");
                        $('#loginModal').modal('show');
                        getVerificationCode();
                        return;
                        break;
                    case 404:
                        showAlert('HTTP响应状态 404 未找到请求的资源，可能引起的原因是请求的资源不存在，请检查请求的资源路径是否正确。', 'danger', true, 3);
                        return;
                        break;
                    case 405:
                        showAlert('HTTP响应状态 405 请求方法不被允许，可能引起的原因是后端定义的请求方式与前端请求方式不一致，请检查请求的方法是否正确。', 'danger', true, 3);
                        break;
                    case 500:
                        showAlert('HTTP响应状态 500 服务内部异常，可能引起的原因是后端服务内部发生异常！请检查后端返回的错误内容并确认后端服务是否正常。', 'danger', true, 3);
                        return;
                        break;
                    case 502:
                        showAlert('HTTP响应状态 502 请求网关异常，可能引起的原因是网关无法请求到后端服务，请检查网关配置是否正确或后端服务是否正常。', 'danger', true, 3);
                        return;
                        break;
                    case 504:
                        showAlert('HTTP响应状态 504 请求响应超时，可能引起的原因是后端服务异常或后端服务调用三方远程服务超时，请检查后端服务是否正常。', 'danger', true, 3);
                        return;
                        break;
                    default:
                        var error = 'HTTP错误:' + response.status + "&nbsp;&nbsp;" + response.statusText;
                        showAlert(error, 'danger', true, 3);
                        return;
                        break;
                }
            }
            return response.json();
        })
        .then(data => {
            //console.log('[fetch]Success:', data);
            return data;
        })
        .catch(error => {
            //console.error('[fetch]Error:', error);
            throw error;
        });
}